package 面试题25_合并两个排序的链表;

/**
 * @Author ：xu_xiaofeng.
 * @Date ：Created in 12:37 2021/3/11
 * @Description：
 */
class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}

public class Solutioin {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }

        ListNode pCurNode1 = l1;
        ListNode pCurNode2 = l2;

        ListNode pMeargeHead = null;
        if (pCurNode1.val <= pCurNode2.val) {
            pMeargeHead = pCurNode1;
            pCurNode1 = pCurNode1.next;
        } else {
            pMeargeHead = pCurNode2;
            pCurNode2 = pCurNode2.next;
        }

        ListNode pMeargeCurNode = pMeargeHead;

        while (pCurNode1 != null && pCurNode2 != null) {
            if (pCurNode1.val <= pCurNode2.val) {
                pMeargeCurNode.next = pCurNode1;
                pCurNode1 = pCurNode1.next;
            } else {
                pMeargeCurNode.next = pCurNode2;
                pCurNode2 = pCurNode2.next;
            }

            pMeargeCurNode = pMeargeCurNode.next;
        }

        // 处理还有剩余节点的情况
        while (pCurNode1 != null) {
            pMeargeCurNode.next = pCurNode1;
            pCurNode1 = pCurNode1.next;
            pMeargeCurNode = pMeargeCurNode.next;
        }

        while (pCurNode2 != null) {
            pMeargeCurNode.next = pCurNode2;
            pCurNode2 = pCurNode2.next;
            pMeargeCurNode = pMeargeCurNode.next;
        }

        return pMeargeHead;
    }
}
